$(function () {
   obj.init();
});
var obj = new function () {
    'use strict';
    return {
        form:null,
        frame:null,
        id:null,
        mConFiles:[],
        mSumFiles:[],
        domName:'',
        init:function () {
            this.id = xhTool.getQuery('id');
            this.form = new xhForm($('#xh_form'));
            this.form.parse();
            this.funObj().loadHight();
            this.frame = $('[name=scheduleFrame]');
            if (info) {
                this.form.fill(info);
                this.mConFiles = info['mConFiles'];
                this.mSumFiles = info['mSumFiles'];
                this.funObj().triggerRoom($('[name=iMeetingRoom]').val());
            } else {
                $('[name=iMeetingRoom]')[0].disabled = true;
            }
            xhFile.load($('#mConFiles ul'), this.mConFiles);
            xhFile.load($('#mSumFiles ul'), this.mSumFiles);
            $("[name=tEndTime],[name=tStartTime]").datetimepicker({format: 'yyyy-mm-dd hh:ii', language: 'zh-CN', minView: "hour", autoclose: true,editable:false});
            this.listener();
        },
        listener:function () {
            var $this = this;

            //返回
            $('#retBtn').click(function () {
                $this.funObj().goToList();
            });

            //会议室选中
            $('[name=iMeetingRoom]').change(function () {
                $this.funObj().triggerRoom($(this).val());
            });

            //文件上传
            $('#file').change(function () {
                if ($('#file').val()) {
                    $this.funObj().fileUpload($(this));
                }
            });

            //参与者
            $('#mParticipant').combotree({
                url:baseUrl+'lm/meeting/getDepStaff',
                valueField:'id',
                textField:'text',
                required:false,
                multiple: true,
                width: ($('#mParticipant').parent().parent().prev().find('td').eq(1).width() -220) +'px',
                height:'34px',
                panelHeight:'300px',
                onLoadSuccess:function (data) {
                    if (info && info['mParticipant']) {
                        $('#mParticipant').combotree('setValues',info['mParticipant']);
                    }
                }
            });
            //保存按钮
            $('#saveBtn').click(function () {
                $this.funObj().submitForm();
            });

            //删除图片按钮
            $('#mConFiles').on('click','.delBtn',function () {
                $this.funObj().delFiles($(this).attr('nodeId'),'mConFiles');
            });
            //删除图片
            $('#mSumFiles').on('click','.delBtn',function () {
                $this.funObj().delFiles($(this).attr('nodeId'),'mSumFiles');
            });

            //开始时间选中
            $("[name=tStartTime]").on('changeDate',function(ev){
                $this.funObj().changeStartTime();
            });

            //结束时间选中
            $("[name=tEndTime]").on('changeDate',function(ev){
                $this.funObj().changeEndTime();
            });
            //上传
            $('.uploadBtn').click(function () {
                $this.domName = $(this).attr('nodeType');
                $('#file').click();
            });
            
            $('#searchText').keyup(function () {
                $this.funObj().searchTree($(this).val());
            })

        },
        funObj:function () {
            var $this = this;
            return {
                loadHight:function () {
                    var height = $(document.body).outerHeight(true) - 20;
                    $('.srcollDiv').attr('style','height: '+height+'px;');
                    window.onresize = function(){  //重新定义界面大小处理
                        var height = $(document.body).outerHeight(true) - 20;
                        $('.srcollDiv').attr('style','height: '+height+'px;');
                    };
                },
                searchTree:function (q) {
                    var t = $('#mParticipant').combotree('tree');
                    t.tree("search", q);
                    $('#mParticipant').combo('showPanel');
                    // $(this).combo('hidePanel', true);
                    // $('#mParticipant').click();
                },
                changeEndTime:function () {
                    if (!endTime) {
                        $('[name=iMeetingRoom]')[0].disabled = true;
                    }
                    var startTime = $("[name=tStartTime]").val();
                    var endTime   = $("[name=tEndTime]").val();
                    if (!startTime) {
                        window.top.xhTop.showError('错误', '请先选择开始时间');
                        $("[name=tEndTime]").val('');
                        return false;
                    }
                    if (startTime && endTime) {
                        var dom = $('[name=iMeetingRoom]');
                        dom[0].disabled = false;
                        xhExtra.ajaxRequest('lm/meeting/filterMeetRoom',{startTime:startTime,endTime:endTime,currentId:$this.id},{},function (res) {
                            var str = '<option value="0" selected style="display: none">请选择</option>';
                            $.each(res,function (id,text) {
                                str += '<option value="'+id+'">'+text+'</option>';
                            });
                            $('[name=iMeetingRoom]').empty().append(str);
                        })
                    }
                },
                changeStartTime:function () {
                    var  startTime = $("[name=tStartTime]").val();
                    $('[name=iMeetingRoom]').val(0);
                    $('[name=iMeetingRoom]')[0].disabled = true;
                    $("[name=tEndTime]").datetimepicker('setStartDate',startTime).val('');
                },
                goToList:function () {
                    window.top.xhTop.getActiveFrame().obj.funObj().backToList();
                },
                triggerRoom:function ($val) {
                    var startTime = $("[name=tStartTime]").val();
                    var endTime   = $("[name=tEndTime]").val();
                    var addressUrl = baseUrl + 'lm/meeting/meetingSchedule?room='+$val+
                        '&startTime='+startTime+'&endTime='+endTime;
                    if ($this.id) {
                        addressUrl += '&currentId=' + $this.id;
                    }
                    $this.frame[0].contentWindow.location = addressUrl;

                },
                fileUpload:function (fileDom) {
                    window.top.swal({
                        title: '上传中！请耐心等待...',
                        showConfirmButton: false,
                        type: 'success',
                        allowOutsideClick: false
                    });
                    var formData = new FormData();
                    var file = $(fileDom)[0].files[0];
                    formData.append('file' , file);
                    $.ajax({
                        url:baseUrl + 'lm/meeting/uploadFile',
                        method:'post',
                        dataType:'json',
                        data:formData,
                        processData:false,
                        contentType:false,
                        complete: function(XMLHttpRequest){
                            window.top.swal.close();
                            var result = XMLHttpRequest.responseJSON || XMLHttpRequest.responseText;
                            if(xhExtra.checkError(result)) return false;
                            if ($this.domName == 'mConFiles') {
                                $this.mConFiles.push(result);
                                xhFile.load($('#mConFiles ul'),$this.mConFiles);
                            } else if ($this.domName == 'mSumFiles') {
                                $this.mSumFiles.push(result);
                                xhFile.load($('#mSumFiles ul'),$this.mSumFiles);
                            }
                        }
                    })
                },
                delFiles:function (index, domName) {
                    if (domName == 'mConFiles') {
                        $this.mConFiles = $this.mConFiles.delete(index);
                        xhFile.load($('#mConFiles ul'), $this.mConFiles);
                    } else if (domName == 'mSumFiles') {
                        $this.mSumFiles = $this.mSumFiles.delete(index);
                        xhFile.load($('#mSumFiles ul'), $this.mSumFiles);
                    }

                },
                submitForm:function () {
                    var mParticipant = $('#mParticipant').combotree('getValues');
                    $this.form.submit('lm/meeting/saveMeeting',{conFiles:$this.mConFiles,sumFiles:$this.mSumFiles,mParticipant:mParticipant},function (res) {
                        window.top.xhTop.showSuccess(res.msg);
                        $this.funObj().goToList();//返回列表
                    })
                }

            }
        }
    }
};

Array.prototype.delete=function(delIndex){
    var temArray=[];
    for(var i=0;i<this.length;i++){
        if(i!=delIndex){
            temArray.push(this[i]);
        }
    }
    return temArray;
};

var xhFile = {
    load:function (dom,files) {
        if (!files) {
            return false;
        }
        if (!(files instanceof Array) ) { //判断是否是数组
            if (typeof(files) === 'string') {
                files = files.split(',');
            } else {
                window.top.xhTop.showError('错误', '传入未知文件类型');
                return false;
            }
        }
        var str = '';
        if (files.length > 0) {
            $.each(files,function (i,item) {
                str +=
                    '<li style="float: left;margin-right:5px; ">\n' +
                    '                                        <span>\n' +
                    '                                            <a target="_blank" href="'+item['url']+'" title="'+item['fileName']+'" href="" class="btn btn-default" style="text-align: center;border: 0px;">\n' +
                    '                                                <i class="fa fa-file-o fa-2x customer-size" aria-hidden="true"></i>\n' +
                    '                                                <br>\n' +
                    '                                                <p style="text-align: center;margin-bottom: 0px;overflow: hidden;width: 30px;font-size: xx-small;">'+item['fileName']+'</p>\n' +
                    '                                            </a>\n' +
                    '                                            <br>\n' +
                    '                                            <a class="delBtn" nodeId="'+i+'" style="text-align: center;width: 60px;margin-bottom: 10px;display: block;cursor: pointer">删除</a>\n' +
                    '                                        </span>\n' +
                    '                                    </li>';
            });
        }
        dom.empty().append(str);
    }
};

(function ($) {
    //combotree可编辑，自定义模糊查询  
    // $.fn.combotree.defaults.editable = true;
    // $.extend($.fn.combotree.defaults.keyHandler, {
    //     query: function (q) {
    //         var t = $(this).combotree('tree');
    //         t.tree("search", q);
    //     }
    // });
    $.extend($.fn.tree.methods, {           /**   
                  * 扩展easyui tree的搜索方法 
                  * @param tree easyui tree的根DOM节点(UL节点)的jQuery对象          * @param searchText 检索的文本 
                  * @param this-context easyui tree的tree对象          */
        search: function (jqTree, searchText) {
            //easyui tree的tree对象。可以通过tree.methodName(jqTree)方式调用easyui tree的方法 
            var tree = this;
            //获取所有的树节点 
            var nodeList = getAllNodes(jqTree, tree);
            //如果没有搜索条件，则展示所有树节点       
            searchText = $.trim(searchText);
            if (searchText == "") {
                for (var i = 0; i < nodeList.length; i++) {
                    $(".tree-node-targeted",
                        nodeList[i].target).removeClass("tree-node-targeted");
                    $(nodeList[i].target).show();
                }
                //展开已选择的节点（如果之前选择了）            
                var selectedNode = tree.getSelected(jqTree);
                if (selectedNode) {
                    tree.expandTo(jqTree, selectedNode.target);
                }
                return;
            }
            //搜索匹配的节点并高亮显示            
            var matchedNodeList = [];
            if (nodeList && nodeList.length > 0) {
                var node = null;
                for (var i = 0; i < nodeList.length; i++) {
                    node = nodeList[i];
                    if (isMatch(searchText, node.text)) {
                        matchedNodeList.push(node);
                    }
                }
                //隐藏所有节点 
                for (var i = 0; i < nodeList.length; i++) {
                    $(".tree-node-targeted", nodeList[i].target).removeClass("tree-node-targeted");
                    $(nodeList[i].target).hide();
                }
                //折叠所有节点 
                tree.collapseAll(jqTree);
                //展示所有匹配的节点以及父节点 


                for (var i = 0; i < matchedNodeList.length; i++) {
                    showMatchedNode(jqTree, tree, matchedNodeList[i]);
                }
            }
        },
        /**   
                 * 展示节点的子节点（子节点有可能在搜索的过程中被隐藏了）        
                 * @param node easyui tree节点         
                 */
        showChildren: function (jqTree, node) {
            //easyui tree的tree对象。可以通过tree.methodName(jqTree)方式调用easyui tree的方法 
            var tree = this;
            //展示子节点 
            if (!tree.isLeaf(jqTree, node.target)) {
                var children = tree.getChildren(jqTree, node.target);
                if (children && children.length > 0) {
                    for (var i = 0; i < children.length; i++) {
                        if ($(children[i].target).is(":hidden")) {
                            $(children[i].target).show();
                        }
                    }
                }
            }
        },
        /**   
                 * 将滚动条滚动到指定的节点位置，使该节点可见（如果有滚动条才滚动，没有滚动条就不滚动） 
                 * @param param {   
        * treeContainer: easyui tree的容器（即存在滚动条的树容器）。如果为null，则取easyui tree的根UL节点的父节点。 
        * argetNode:  将要滚动到的easyui tree节点。如果targetNode为空，则默认滚动到当前已选中的节点，如果没有选中的节点，则不滚动          * }             */
        scrollTo: function (jqTree, param) {
            //easyui tree的tree对象。可以通过tree.methodName(jqTree)方式调用easyui tree的方法 
            var tree = this;
            //如果node为空，则获取当前选中的node   
            var targetNode = param && param.targetNode ? param.targetNode : tree.getSelected(jqTree);
            if (targetNode != null) {
                //判断节点是否在可视区域                 var root = tree.getRoot(jqTree);   
                var $targetNode = $(targetNode.target);
                var container = param && param.treeContainer ? param.treeContainer : jqTree.parent();
                var containerH = container.height();
                var nodeOffsetHeight = $targetNode.offset().top - container.offset().top;
                if (nodeOffsetHeight > (containerH - 30)) {
                    var scrollHeight = container.scrollTop() + nodeOffsetHeight - containerH + 30;
                    container.scrollTop(scrollHeight);
                }
            }
        }
    });
    /**   
              * 展示搜索匹配的节点      */
    function showMatchedNode(jqTree, tree, node) {
        //展示所有父节点 
        $(node.target).show();
        $(".tree-title", node.target).addClass("tree-node-targeted");
        var pNode = node;
        while ((pNode = tree.getParent(jqTree, pNode.target))) {
            $(pNode.target).show();
        }
        //展开到该节点 
        tree.expandTo(jqTree, node.target);
        //如果是非叶子节点，需折叠该节点的所有子节点      
        if (!tree.isLeaf(jqTree, node.target)) {
            tree.collapse(jqTree, node.target);
        }
    }
    /**   
          * 判断searchText是否与targetText匹配 
          * @param searchText 检索的文本      * @param targetText 目标文本 
          * @return true-检索的文本与目标文本匹配；否则为false.        
         */
    function isMatch(searchText, targetText) {
        return $.trim(targetText) != "" && targetText.indexOf(searchText) != -1;
    }
    /**   
          * 获取easyui tree的所有node节点      */
    function getAllNodes(jqTree, tree) {
        var allNodeList = jqTree.data("allNodeList");
        if (!allNodeList) {
            var roots = tree.getRoots(jqTree);
            allNodeList = getChildNodeList(jqTree, tree, roots);
            jqTree.data("allNodeList", allNodeList);
        }
        return allNodeList;
    }
    /**   
          * 定义获取easyui tree的子节点的递归算法      */
    function getChildNodeList(jqTree, tree, nodes) {
        var childNodeList = [];
        if (nodes && nodes.length > 0) {
            var node = null;
            for (var i = 0; i < nodes.length; i++) {
                node = nodes[i];
                childNodeList.push(node);
                if (!tree.isLeaf(jqTree, node.target)) {
                    var children = tree.getChildren(jqTree, node.target);
                    childNodeList = childNodeList.concat(getChildNodeList(jqTree, tree, children));
                }
            }
        }
        return childNodeList;
    }
})(jQuery);

